package com.bianmaba.dc.controller;

import com.bianmaba.dc.bean.CollectionRequest;
import com.bianmaba.dc.bean.CollectorResponse;
import com.bianmaba.dc.bean.TaskStatus;
import com.bianmaba.dc.task.CollectionTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 采集器控制器，如果不是必要，不需要重写此类
 * <pre>
 *     控制器包含3个接口：
 *     collect:采集请求接口
 *     status:采集状态查询接口
 *     stop:任务终止接口
 * </pre>
 */
@RestController
@RequestMapping("dts")
@Scope("singleton")
public class CollectionController {
    private Map<String, CollectionTask> tasks = new HashMap();
    private Map<String, Future> futures = new HashMap();
    private ExecutorService executorService = Executors.newCachedThreadPool();

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @RequestMapping(value = "collect")
    public CollectorResponse<Boolean> collect(@RequestBody CollectionRequest collectionRequest, HttpServletRequest servletRequest) {
        synchronized (CollectionController.class) {
            String message = String.format("采信器：采集请求已经收到，URL=%s", servletRequest.getRequestURL());
            CollectionTask task = new CollectionTask(collectionRequest);
            capableBeanFactory.autowireBean(task);
            Future future = executorService.submit(task);
            tasks.put(collectionRequest.getTaskInstanceId(), task);
            futures.put(collectionRequest.getTaskInstanceId(), future);

            return (CollectorResponse) CollectorResponse.of(true).setData(true).setResult(message);
        }
    }

    @RequestMapping("status")
    public CollectorResponse<Integer> status(String taskInstanceId) {
        CollectionTask task = tasks.get(taskInstanceId);
        if (task != null) {
            List<String> logs = task.pollLogs();
            TaskStatus status = task.getStatus();
            //判断任务状态，如果任务已经不是运行状态则结束
            if (!status.equals(TaskStatus.RUNNING) && logs.isEmpty()) {
                tasks.remove(taskInstanceId);
                futures.remove(taskInstanceId);
                return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(status).setData(task.getDatas());
            } else {
                return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(TaskStatus.RUNNING).addMessages(logs).setData(task.getDatas());
            }
        } else {
            return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(TaskStatus.SYSTEM_TERMINATED).addMessage("指定任务不存在：" + taskInstanceId);
        }
    }

    @RequestMapping("stop")
    public CollectorResponse<Integer> stop(String taskInstanceId, HttpServletRequest servletRequest) {
        Future future = futures.get(taskInstanceId);
        if (future != null) {
            CollectionTask task = tasks.get(taskInstanceId);
            if (task.getStatus().getIndex() != TaskStatus.RUNNING.getIndex()) {
                List<String> logs = task.pollLogs();
                return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(tasks.get(taskInstanceId).getStatus()).addMessages(logs);
            } else {
                future.cancel(true);
                String message = String.format("采信器：终止采集请求已经收到，URL=%s,taskInstanceId=%s", servletRequest.getRequestURL(), taskInstanceId);
                return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(tasks.get(taskInstanceId).getStatus()).addMessage(message);
            }
        }
        return (CollectorResponse) CollectorResponse.of(true).setTaskStatus(TaskStatus.SYSTEM_TERMINATED).addMessage("采信器：指定任务不存在，taskInstanceId=" + taskInstanceId);
    }
}
